"""
FastAPI routes for the demo application
"""

from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from typing import List, Optional, Dict, Any
import httpx
from .proxy_routes import get_proxy_router, setup_proxy_manager

# Create API router
api_router = APIRouter()

# Global variable to store proxy manager instance
_proxy_manager = None


# Pydantic models for API requests/responses
class HealthResponse(BaseModel):
    status: str
    message: str


class EchoRequest(BaseModel):
    message: str
    metadata: Optional[Dict[str, Any]] = None


class EchoResponse(BaseModel):
    original_message: str
    echo: str
    metadata: Optional[Dict[str, Any]] = None


class MCPStatusResponse(BaseModel):
    mcp_available: bool
    mcp_tools_count: int
    mcp_resources_count: int
    mcp_prompts_count: int


@api_router.get("/health", response_model=HealthResponse)
async def api_health():
    """API health check endpoint"""
    return HealthResponse(status="healthy", message="FastAPI is running")


@api_router.post("/echo", response_model=EchoResponse)
async def echo_message(request: EchoRequest):
    """Echo a message back with some processing"""
    return EchoResponse(
        original_message=request.message,
        echo=f"Echo: {request.message}",
        metadata=request.metadata,
    )


@api_router.get("/mcp/status", response_model=MCPStatusResponse)
async def mcp_status(request: Request):
    """Get status of the MCP server"""
    try:
        # Try to access the MCP server from app state
        mcp_server = getattr(request.app.state, "mcp_server", None)

        if mcp_server is None:
            return MCPStatusResponse(
                mcp_available=False,
                mcp_tools_count=0,
                mcp_resources_count=0,
                mcp_prompts_count=0,
            )

        # Get counts from MCP server managers
        tools_count = len(mcp_server.tool_manager.get_tools())
        resources_count = len(mcp_server.resource_manager.get_resources())
        prompts_count = len(mcp_server.prompt_manager.get_prompts())

        return MCPStatusResponse(
            mcp_available=True,
            mcp_tools_count=tools_count,
            mcp_resources_count=resources_count,
            mcp_prompts_count=prompts_count,
        )
    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"Failed to get MCP status: {str(e)}"
        )


@api_router.get("/demo/users")
async def list_demo_users():
    """Demo endpoint that returns sample user data"""
    return [
        {"id": 1, "name": "Alice", "email": "alice@example.com", "active": True},
        {"id": 2, "name": "Bob", "email": "bob@example.com", "active": True},
        {"id": 3, "name": "Charlie", "email": "charlie@example.com", "active": False},
    ]


@api_router.get("/demo/users/{user_id}")
async def get_demo_user(user_id: int):
    """Get a specific demo user by ID"""
    users = {
        1: {"id": 1, "name": "Alice", "email": "alice@example.com", "active": True},
        2: {"id": 2, "name": "Bob", "email": "bob@example.com", "active": True},
        3: {
            "id": 3,
            "name": "Charlie",
            "email": "charlie@example.com",
            "active": False,
        },
    }

    if user_id not in users:
        raise HTTPException(status_code=404, detail="User not found")

    return users[user_id]


@api_router.get("/demo/weather/{city}")
async def get_demo_weather(city: str):
    """Demo weather endpoint (simulated data)"""
    # Simulate different weather for different cities
    weather_data = {
        "london": {"temperature": 15, "condition": "Cloudy", "humidity": 80},
        "paris": {"temperature": 18, "condition": "Sunny", "humidity": 60},
        "tokyo": {"temperature": 22, "condition": "Rainy", "humidity": 90},
        "newyork": {"temperature": 20, "condition": "Sunny", "humidity": 50},
    }

    city_lower = city.lower()
    if city_lower in weather_data:
        return {"city": city.title(), **weather_data[city_lower], "unit": "celsius"}
    else:
        # Default weather for unknown cities
        return {
            "city": city.title(),
            "temperature": 20,
            "condition": "Unknown",
            "humidity": 70,
            "unit": "celsius",
        }


def setup_proxy_routes(proxy_manager):
    """Setup proxy API routes with the given proxy manager."""
    global _proxy_manager
    _proxy_manager = proxy_manager

    # Setup proxy manager for proxy routes
    setup_proxy_manager(proxy_manager)

    # Include proxy router with separate prefix
    api_router.include_router(get_proxy_router())


def get_api_router():
    """Get the configured API router."""
    return api_router
